import React, { useState, useEffect } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import {
  View,
  Image,
  Text,
  RadioGroup,
  Radio,
  Picker,
  Button,
} from "@tarojs/components";
import { AtForm, AtInput, AtToast, AtList, AtListItem } from "taro-ui";

import api from "@api/api.js";
import { uploadImgs } from "@util/util";
import "./index.less";

export default () => {
  const [dtl, setDtl] = useState({});
  const [toast, setToast] = useState({ text: "", isOpened: false });
  const [sysParam, setSysParam] = useState({ order_sex: [] });
  useDidShow(() => {
    getSysParam();
    getDentistry();
  });
  // 获取用户信息
  const getDentistry = async (param) => {
    const { data } = await api.getDentistry(param);
    setDtl({ ...data });
  };
  // 获取数据字典
  const getSysParam = async () => {
    const { data } = await api.getSysParam(["position", "order_sex"]);
    setSysParam(data);
  };
  // 保存
  const saveDentistry = async () => {
    const { data, code } = await api.saveDentistry({ ...dtl });
    if (code == 200) {
      setToast({
        text: "保存成功",
        isOpened: true,
        onClose: () => {
          Taro.switchTab({
            url: `/pages/my/index`,
          });
        },
      });
    }
  };
  // 上传头像
  const uploadHeader = () => {
    Taro.chooseImage({
      count: 1,
      success(res) {
        Taro.uploadFile({
          url: api.bseUrl + "/sys/upload/single",
          filePath: res.tempFilePaths[0],
          header: {
            Authorization: Taro.getStorageSync("token"),
          },
          name: "file",
          success(resData) {
            const {
              data: { path },
            } = JSON.parse(resData.data);
            setDtl({ ...dtl, headimgurl: path });
          },
        });
      },
    });
  };
  // 表单改变
  const handleChange = (key, value) => {
    dtl[key] = value;
    setDtl(dtl);
  };
  // 下拉改变
  const pickerChange = (value) => {
    const index = value.detail.value;
    dtl.position = sysParam.position[index].paramCode;
    dtl.positionDesc = sysParam.position[index].paramDesc;
    setDtl({ ...dtl });
  };
  // 单选改变
  const radioChange = (value) => {
    dtl.sex = value.detail.value;
    setDtl(dtl);
  };
  // 获取手机号
  const getPhone = (e) => {
    Taro.login({
      async success(res) {
        const { encryptedData, iv } = e.detail;
        const { data, errorMessage, code } = await api.getPhoneNumber({
          encryptedData,
          iv,
          code: res.code,
        });
        if (code == 200) {
          console.log(data);
          setDtl({ ...dtl, phone: data });
        } else {
          setToast({
            text: errorMessage,
            isOpened: true,
          });
        }
      },
    });
  };
  return (
    <View className="bgBox">
      <AtToast {...toast}></AtToast>
      <View className="listBox">
        <View className="upload">
          <Image src={api.bseUrl + dtl.headimgurl} />
          <View>
            <View className="UploadBtn" onClick={uploadHeader}>
              点击编辑头像
            </View>
          </View>
        </View>
        <AtForm onSubmit={saveDentistry.bind(this)}>
          <View className="list input">
            <View className="fontBold">
              姓名<Text>*</Text>
            </View>
            <AtInput
              placeholder="请输入姓名"
              onChange={handleChange.bind(this, "name")}
              name="name"
              value={dtl.name}
            />
          </View>
          <View className="list myRadio radio">
            <View className="fontBold">
              性别<Text>*</Text>
            </View>
            <View className="radios">
              <RadioGroup onChange={radioChange}>
                {sysParam.order_sex.map((item) => {
                  return (
                    <Radio
                      value={item.paramCode}
                      checked={dtl.sex == item.paramCode}
                    >
                      {item.paramDesc}
                    </Radio>
                  );
                })}
              </RadioGroup>
            </View>
          </View>
          <View className="list">
            <View className="fontBold">职务</View>
            <Picker
              mode="selector"
              range={sysParam.position}
              rangeKey="paramDesc"
              onChange={pickerChange}
            >
              <View className="pickerInput">
                {dtl.position
                  ? sysParam?.position?.find(
                      (item) => item.paramCode === dtl.position
                    ).paramDesc
                  : "请选择职务"}
              </View>
            </Picker>
          </View>
          <View className="list input">
            <View className="fontBold">任职单位</View>
            <AtInput
              placeholder="请输入任职单位"
              onChange={handleChange.bind(this, "hospital")}
              name="hospital"
              value={dtl.hospital}
            />
          </View>
          <View className="list input">
            <View className="fontBold">
              擅长领域<Text>*</Text>
            </View>
            <AtInput
              placeholder="请输入擅长领域"
              onChange={handleChange.bind(this, "expertise")}
              name="expertise"
              value={dtl.expertise}
            />
          </View>
          <View className="list input">
            <View className="fontBold">
              手机号<Text>*</Text>
            </View>
            <AtInput
              placeholder="请点击授权手机号"
              name="phone"
              disabled
              value={dtl.phone}
            />
            <Button
              className="phone"
              onGetPhoneNumber={getPhone}
              openType="getPhoneNumber"
            >
              授权手机号
            </Button>
          </View>
        </AtForm>
      </View>
      <View className="bottomBtn" onClick={saveDentistry}>
        <View>确认编辑</View>
      </View>
    </View>
  );
};
